function [tra]=leak_corr(dfile, n)
%leak correction on current traces
%measures the mean current at a hyperpolarizing step and estimates the 
%leak conductance and leak current
%A=p(1)=g_leak, b=p(2)=I leak
%
%does a linear regression fit Ax+b and subtracts it from the data
%looks at data between l1 and l2 ms
%for resting pot, lt3 is used
%looks at data between -110 and -65 mV

global CURRENT VOLTAGE WCHAN
global CONTROL

tra=0;
v1=number_arg(CONTROL(n).vlmax); %usually -90 mV
v2=number_arg(CONTROL(n).vlmin); %usually -65 mV
if(v1 > v2)  % swap arguments
   t = v2;
   v2=v1;
   v1=t;
end
QueMessage(sprintf('Leak Corrections: v1=%8.1f v2=%8.1f', v1, v2));
rate = dfile.rate(1)*dfile.nr_channel/1000;
[step] = convert_steps_to_times(n);
lwin = number_arg(CONTROL(n).leakwin);
if(lwin==0) 
   QueMessage(sprintf('No window for leak correction'));
   return;
end
lt1 = step(lwin).begin+4; %0.5*step(lwin).dur;
lt2 = step(lwin).begin+5; %step(lwin).dur*0.95;
lt3 = 0.5*step(1).dur; % use half of the holding step duration
t1=floor(lt1./rate); %begin of mean
t2=floor(lt2./rate); %end of mean
t3=floor(lt3./rate); % holding voltage
if(t1<=0) t1=1; end;
if(t2<=0) t2=1; end;
if(t3<=0) t3=1; end;
%disp(sprintf('rate %f lt1: %f t1: %d  lt2: %f t2: %d lt3: %f t3: %d', rate, lt1, t1, lt2, t2, lt3, t3))
[recs,pts]=size(CURRENT);
if(t1 > pts | t2 > pts)
   QueMessage(' Bad Window for Leak Correction');
   return;
end;
volt=mean(VOLTAGE(:,t1:t2)');
%figure out which traces in the voltage window
v_ind=find(volt > v1 & volt < v2);
if length(v_ind) < 2
   %no data in range
   p(1)=0;
   p(2)=0;
   tra=0;	
   QueMessage('No data to correct!');
   return;
else
   mean_volt=volt(v_ind);
   mean_cur=mean(CURRENT(v_ind,t1:t2)');
   [i,tra]=size(mean_volt);
   [p,s]=polyfit(mean_volt,mean_cur,1);
   %A=p(1); b=p(2);
   
   %correct currents
   CURRENT(:,1:pts)=CURRENT(:,1:pts)-(VOLTAGE(:,1:pts)*p(1)+p(2));
end
CONTROL(n).Vm0 = mean(mean(VOLTAGE(:,1:t3)'));
CONTROL(n).iHold = CONTROL(n).Vm0*p(1)+p(2);
CONTROL(n).Rin = p(1);
%   disp(sprintf('Leak results: Ntraces: %d Rin: %s  iHold; %s  Vm0: %s', tra, ctl(n).Rin, ctl(n).iHold, ctl(n).Vm0))
return

